//
//  PickerViewController.m
//  E-Book
//

#import "PickerViewController.h"

@interface PickerViewController ()
{
    //年份输入框
    UITextField * _textYear;
    //类目输入框
    UITextField * _textName;
    //筛选背景
    UIView * _backView;
    //筛选数组
    NSMutableArray * _textData1;
    NSMutableArray * _textData2;
    NSDictionary * _textData2Dic;
}
//搜索限定条件框－年份/类目选择器
@property (nonatomic, strong) UIPickerView *pickerView;
@end

@implementation PickerViewController
//视图加载完成时被调用，开始自定义数据以及动态创建追加其他控件
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self searchShow];
}

//布局方法。搜索条件视图
-(void)searchShow{
    _backView = [[UIView alloc]init];
    _backView.frame = CGRectMake(0, 33, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 97);
    _backView.clipsToBounds = YES;
    _backView.backgroundColor = [UIColor colorWithRed:1.0/255 green:1.0/255 blue:1.0/255 alpha:0.5];
    [self.view addSubview:_backView];
    
    UIView * showView = [[UIView alloc]init];
    //根据屏幕宽度，ipad和iphone分别进行布局
    if (KScreenIpad) {
        showView.frame = CGRectMake(15, 0, 320, 341);
    }
    else {
        showView.frame = CGRectMake(0, 0, 320, 341);
    }
    showView.clipsToBounds = YES;
    showView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"searchbg.png"]];
    [_backView addSubview:showView];
    //清空按钮
    UIButton * clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //根据屏幕宽度，ipad和iphone分别进行布局
    if (KScreenIpad) {
        clearBtn.frame = CGRectMake(0, 15, 108, 42);
    }else{
        clearBtn.frame = CGRectMake(15, 15, 43, 42);
    }
    [clearBtn setTitle:@"清空" forState:UIControlStateNormal];
    clearBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [clearBtn addTarget:self action:@selector(clearBtn:) forControlEvents:UIControlEventTouchUpInside];
    [clearBtn setTitleColor:[UIColor colorWithRed:102.0/255 green:174.0/255 blue:241.0/255 alpha:1] forState:UIControlStateNormal];
    clearBtn.backgroundColor = [UIColor clearColor];
    [showView addSubview:clearBtn];
    //完成按钮
    UIButton * downBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //根据屏幕宽度，ipad和iphone分别进行布局
    if (KScreenIpad) {
        downBtn.frame = CGRectMake(212, 15, 108, 42);
    }else{
        downBtn.frame = CGRectMake(262, 15, 43, 42);
    }
    downBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [downBtn setTitle:@"完成" forState:UIControlStateNormal];
    [downBtn addTarget:self action:@selector(downBtn:) forControlEvents:UIControlEventTouchUpInside];
    [downBtn setTitleColor:[UIColor colorWithRed:89.0/255 green:165.0/255 blue:88.0/255 alpha:1] forState:UIControlStateNormal];
    downBtn.backgroundColor = [UIColor clearColor];
    [showView addSubview:downBtn];
    //年份列表
    _textYear =[[UITextField alloc]initWithFrame:CGRectMake(16, 74, 131, 30)];
    [showView addSubview:_textYear];
    _textYear.placeholder = @"年份";
    _textYear.tag = 2;
    _textYear.clearButtonMode = UITextFieldViewModeAlways;
    _textYear.delegate = self;
    _textYear.layer.cornerRadius = 16.0;
    _textYear.backgroundColor = [UIColor colorWithRed:230.0/255 green:230.0/255 blue:230.0/255 alpha:1];
    _textYear.textColor = [UIColor colorWithRed:102.0/255 green:174.0/255 blue:241.0/255 alpha:1];
    _textYear.returnKeyType = UIReturnKeySearch;
    _textYear.font =[UIFont systemFontOfSize:21];
    _textYear.textAlignment = NSTextAlignmentCenter;
    //分类列表
    _textName =[[UITextField alloc]initWithFrame:CGRectMake(170, 74, 131, 30)];
    [showView addSubview:_textName];
    _textName.placeholder = @"类目";
    _textName.tag = 3;
    _textName.clearButtonMode = UITextFieldViewModeAlways;
    _textName.delegate = self;
    _textName.layer.cornerRadius = 16.0;
    _textName.backgroundColor = [UIColor colorWithRed:230.0/255 green:230.0/255 blue:230.0/255 alpha:1];
    _textName.textColor = [UIColor colorWithRed:102.0/255 green:174.0/255 blue:241.0/255 alpha:1];
    _textName.returnKeyType = UIReturnKeySearch;
    _textName.font =[UIFont systemFontOfSize:21];
    _textName.textAlignment = NSTextAlignmentCenter;
    //获取当前年份
    NSDate *  readtime = [NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY"];
    NSString *locationString=[dateformatter stringFromDate:readtime];
    int currentYear = locationString.intValue;
    //数据
    _textData1 = [[NSMutableArray alloc]initWithObjects:[NSString stringWithFormat:@"%d",currentYear-4],[NSString stringWithFormat:@"%d",currentYear-3],[NSString stringWithFormat:@"%d",currentYear-2],[NSString stringWithFormat:@"%d",currentYear-1],[NSString stringWithFormat:@"%d",currentYear],[NSString stringWithFormat:@"%d",currentYear+1],[NSString stringWithFormat:@"%d",currentYear+2],[NSString stringWithFormat:@"%d",currentYear+3],[NSString stringWithFormat:@"%d",currentYear+4], nil];
//    _textData2 = [[NSMutableArray alloc]initWithObjects:@"名人传记",@"期刊杂志",@"IPAD使用",@"事实新闻",@"经营管理", nil];
    _textData2 = [[NSMutableArray alloc]initWithObjects:@"IPAD使用",@"商品话术",@"营销管理", nil];
    _textData2Dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"0",@"1",@"2", nil] forKeys:[NSArray arrayWithObjects:@"IPAD使用",@"商品话术",@"营销管理", nil]];
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
    //这里设置了就可以自定义高度了，一般默认是无法修改其216像素的高度
    self.pickerView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    self.pickerView.dataSource = self;
    self.pickerView.tag = 1;
    [self.pickerView selectRow:_textData1.count/2 inComponent:0 animated:NO];
    [self.pickerView selectRow:0 inComponent:1 animated:NO];//_textData2.count/2
    //设置代理
    self.pickerView.delegate = self;
    //根据屏幕宽度，ipad和iphone分别进行布局
    if (KScreenIpad) {
        self.pickerView.frame = CGRectMake(-15, 120, showView.frame.size.width, 183);
    }
    else {
        self.pickerView.frame = CGRectMake(-15, 120, showView.frame.size.width, 183);
    }
    //这个最好写
    self.pickerView.showsSelectionIndicator = YES;
    [showView addSubview:self.pickerView];
}

//释放键盘方法
-(void)hideKeyboard{
    [self checkInput];
    [_textYear resignFirstResponder];
    [_textName resignFirstResponder];
}

//输入框内容处理方法
-(void)checkInput{
    bool clearsys = YES;
    //遍历年份
    for (NSString *strYear in _textData1) {
        //存在年份和输入框内容匹配
        if ([[strYear stringByAppendingString:@"年"] isEqualToString:_textYear.text]) {
            clearsys = NO;
            break;
        }
    }
    //不存在年份和输入框内容匹配
    if (clearsys) {
        //输入框内容清空
        _textYear.text = @"";
    }
    //输入内容和所有类目都不匹配
    if (![_textName.text isEqualToString:@""] && ![_textData2Dic objectForKey:_textName.text]) {
        //输入框内容清空
        _textName.text = @"";
    }
}

//按钮点击方法。清空搜索条件中的内容。sender清空按钮
-(void)clearBtn:(UIButton *)sender{
    _textYear.text = @"";
    _textName.text = @"";
    [_textYear resignFirstResponder];
    [_textName resignFirstResponder];
    [self.delegate clearButton:sender clickedInPickerViewController:self];
}
//按钮点击方法。记住搜索条件并使条件选择框消失。sender完成按钮
-(void)downBtn:(UIButton *)sender{
    [self checkInput];
    [_textYear resignFirstResponder];
    [_textName resignFirstResponder];
    [self.delegate doneButton:sender clickedInPickerViewController:self];
}
//响应方法。有触摸操作时调用。touches触摸集合；event事件
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch=[[event allTouches] anyObject];
    if (touch.tapCount >=1) {
        [self checkInput];
        [_textYear resignFirstResponder];
        [_textName resignFirstResponder];
    }
}
//“年份”，“类目”输入框点击清除按钮时调用，把真正用于搜索的条件清掉。
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    //判断是哪个输入框
    switch (textField.tag) {
        //年份
        case 2:
            [self.delegate textYearChanged:@"" inPickerViewController:self];
            break;
        //类目
        case 3:
            [self.delegate textNameChanged:@"0" inPickerViewController:self];
            break;
        default:
            break;
    }
    return YES;
}
#pragma mark - UIPickerViewDelegate
//选择器的代理方法。返回选择器个数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}
//选择器的代理方法。返回选择器行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return _textData1.count;
            break;
        case 1:
            return _textData2.count;
            break;
        default:
            break;
    }
    return 0;
    
}
//选择器的代理方法。返回选择器的具体显示值
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return _textData1[row];
            break;
        case 1:
            return _textData2[row];
            break;
        default:
            break;
    }
    return 0;
}
//选择器的代理方法。选择器改变时调用。pickerView选择器；row选中的行；component区分选择器的变量
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component) {
        case 0:{
            _textYear.text = [_textData1[row] stringByAppendingString:@"年"];
            [self.delegate textYearChanged:_textData1[row] inPickerViewController:self];
        }
            break;
        case 1:{
            _textName.text = _textData2[row];
            [self.delegate textNameChanged:_textData2Dic[_textData2[row]] inPickerViewController:self];
        }
            break;
        default:
            break;
    }
}

//内存不足时被调用
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
